// src/monaco/arktsLanguage.ts
import type * as monacoEditor from "monaco-editor";
import { commonKeywords, supportKeywords, greenKeywords, arktsKeywords, styleKeywords } from './keyword'
export function registerArkTS(monaco: typeof monacoEditor) {

  // 注册自定义语言
  monaco.languages.register({ id: "arkts" });
  // 注册 arkts 补全
  monaco.languages.registerCompletionItemProvider("arkts", {

    provideCompletionItems: (model, position) => {
      const word = model.getWordUntilPosition(position);
      const range = {
        startLineNumber: position.lineNumber,
        endLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endColumn: word.endColumn,
      };
      const arktsArr = arktsKeywords.map((item) => ({ label: item, kind: monaco.languages.CompletionItemKind.Keyword, insertText: item, detail: "", range, sortText: '0' }))
      const otherArr = supportKeywords.map((item) => ({ label: item, kind: monaco.languages.CompletionItemKind.Keyword, insertText: item + '(){}', detail: "", range, sortText: '1' }))
      const styleArr = styleKeywords.map((item) => ({ label: item, kind: monaco.languages.CompletionItemKind.Keyword, insertText: item + '()', detail: "", range, sortText: '1' }))
      const suggestions = [...arktsArr, ...styleArr, ...otherArr]
      return { suggestions };
    },
  });
  monaco.languages.setLanguageConfiguration("arkts", {
    autoClosingPairs: [
      { open: "{", close: "}" },
      { open: "(", close: ")" },
      { open: "[", close: "]" },
      { open: '"', close: '"' },
      { open: "'", close: "'" },
    ],
  })

  // 设置语法高亮规则
  monaco.languages.setMonarchTokensProvider("arkts", {
    keywords: commonKeywords,
    greenKeywords,

    tokenizer: {
      root: [
        [/\/\/.*/, "comment"],               // 单行注释
        [/\/\*/, { token: "comment", next: "@comment" }], // 多行注释
        [/@?[a-zA-Z_$][\w$]*/, {
          cases: {
            "@keywords": "keyword",
            "@greenKeywords": "greenKeywords",
            "@default": "identifier"
          }
        }],
        [/"[^"]*"/, "string"],               // 字符串
        [/\d+/, "number"],                   // 数字
      ],
      comment: [
        [/[^\/*]+/, "comment"],
        [/\*\//, { token: "comment", next: "@pop" }],
        [/[\/*]/, "comment"]
      ]
    }
  });


  // 定义自定义主题
  monaco.editor.defineTheme("arkui-dark", {
    base: "vs-dark",
    inherit: true,
    rules: [
      { token: "comment", foreground: "6A9955", fontStyle: "italic" }, // 注释绿色
      { token: "blueKeyword", foreground: "569CD6" },                  // 蓝色关键字
      { token: "greenKeywords", foreground: "3DC9A2" },                 // 绿色关键字
      { token: "string", foreground: "CE9178" },                       // 字符串橙色
      { token: "number", foreground: "B5CEA8" },                       // 数字高亮
      { token: "identifier", foreground: "FFFFFF" },                   // 普通标识符白色
    ],
    colors: {}
  });


}


let tsModel: monacoEditor.editor.ITextModel | null = null;

/**
 * 初始化 TS 隐藏模型，用于类型检查
 * @param monaco Monaco 实例
 * @param dtsText d.ts 类型声明内容
 */
export function setupTSModel(monaco: typeof monacoEditor, dtsText: string) {
  if (tsModel) return; // 已经创建过了

  // 创建 TS 模型（隐藏，不显示在编辑器里）
  tsModel = monaco.editor.createModel(
    "", // 初始内容为空
    "typescript",
    monaco.Uri.parse("file://model.ts") // 内存路径
  );

  // 注入类型声明（declare class / interface 等）
  monaco.languages.typescript.typescriptDefaults.addExtraLib(
    dtsText,
    "file://commonStyle.d.ts"
  );

  // 可选：TS 编译器配置
  monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
    target: monaco.languages.typescript.ScriptTarget.ESNext,
    allowNonTsExtensions: true,
    strict: true,
    noImplicitAny: false,
    moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
  });
}

/**
 * 获取 TS 模型实例
 */
export function getTSModel() {
  return tsModel;
}

export const arktsValidator = (editor: monacoEditor.editor.IStandaloneCodeEditor, monaco: typeof monacoEditor) => {
  if (!tsModel) return;

  let timeout: number;
  editor.onDidChangeModelContent(() => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      const arktsModel = editor.getModel();
      if (!arktsModel) return;

      // 同步到 TS 模型
      tsModel?.setValue(arktsModel.getValue());

      // 获取 TS 错误
      const tsMarkers = monaco.editor.getModelMarkers({ resource: tsModel?.uri });

      // 映射到 ArkTS 编辑器
      const markers = tsMarkers.map(m => ({
        startLineNumber: m.startLineNumber,
        startColumn: m.startColumn,
        endLineNumber: m.endLineNumber,
        endColumn: m.endColumn,
        message: m.message,
        severity: m.severity
      }));

      monaco.editor.setModelMarkers(arktsModel, "arkts-ts", markers);
    }, 200); // debounce 避免每次按键都触发
  });
}